package com.cwx.mychat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cwx.mychat.controller.UserContactCategoryController;
import com.cwx.mychat.entity.constant.CodeConstant;
import com.cwx.mychat.entity.enums.ExceptionBizCodeEnum;
import com.cwx.mychat.entity.enums.UserContactTypeEnum;
import com.cwx.mychat.entity.po.UserContactCategory;
import com.cwx.mychat.exception.BusinessException;
import com.cwx.mychat.mappers.UserContactCategoryMapper;
import com.cwx.mychat.service.UserContactCategoryService;
import com.cwx.mychat.utils.R;
import com.cwx.mychat.utils.common.CommonUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 作者： cwx
 * 时间： 2024/12/11 17:23
 * 版本： 1.0
 * 注释：
 */
@Slf4j
@Service
public class UserContactCategoryServiceImpl extends ServiceImpl<UserContactCategoryMapper, UserContactCategory> implements UserContactCategoryService {

    @Autowired
    private UserContactCategoryMapper userContactCategoryMapper;

    @Override
    public R getAllGroup(String userId) {
        List<UserContactCategory> userContactCategories = userContactCategoryMapper.selectList(new LambdaQueryWrapper<UserContactCategory>()
                        .select(UserContactCategory::getCategoryId, UserContactCategory::getCategoryName, UserContactCategory::getSort, UserContactCategory::getUserId)
                        .eq(UserContactCategory::getUserId, userId)
                        .eq(UserContactCategory::getType, UserContactTypeEnum.USER.getType()));
        return R.ok().put(CodeConstant.RESULT_MSG, userContactCategories);

    }

    @Override
    public R getAllGroupCategory(String userId) {
        List<UserContactCategory> userContactCategories = userContactCategoryMapper.selectList(new LambdaQueryWrapper<UserContactCategory>()
                .select(UserContactCategory::getCategoryId, UserContactCategory::getCategoryName, UserContactCategory::getSort, UserContactCategory::getUserId)
                .eq(UserContactCategory::getUserId, userId)
                .eq(UserContactCategory::getType, UserContactTypeEnum.GROUP.getType()));
        return R.ok().put(CodeConstant.RESULT_MSG, userContactCategories);
    }

    @Override
    public int createGroup(String userId, UserContactCategory userContactCategory) {
        userContactCategory.setCreateTime(new Date());
        userContactCategory.setUpdateTime(new Date());
        userContactCategory.setUserId(userId);
        return userContactCategoryMapper.insert(userContactCategory);
    }

    @Override
    public void addGroup(String groupId, String userId, String receiveId) throws BusinessException {
        UserContactCategory userContactCategory = userContactCategoryMapper.selectOne(new LambdaQueryWrapper<UserContactCategory>()
                .eq(UserContactCategory::getCategoryId, groupId));
        List<String> userIds = new ArrayList<>();
        userIds.add(receiveId);
        UserContactTypeEnum typeEnum = UserContactTypeEnum.getPrefix(receiveId);
        if(typeEnum == null){
            throw new BusinessException(ExceptionBizCodeEnum.USER_ID_FORMAT_EXCEPTION);
        }

        if(UserContactTypeEnum.USER == typeEnum){
            if(userContactCategory.getUserCategory() != null){
                ObjectMapper objectMapper = new ObjectMapper();
                try{
                    List<String> list = objectMapper.readValue(userContactCategory.getUserCategory(), new TypeReference<List<String>>() {});
                    //跟userIds合并
                    list.addAll(userIds);
                    //转化为字符串
                    String str = objectMapper.writeValueAsString(list);
                    userContactCategory.setUserCategory(str);
                }catch (Exception e){
                    log.error("添加分组失败", e);
                    userContactCategory.setUserCategory(userIds.toString());
                }
            }
            userContactCategory.setUserCategory(userIds.toString());
        }
        if(UserContactTypeEnum.GROUP == typeEnum){
            if(userContactCategory.getGroupCategory() != null){
                ObjectMapper objectMapper = new ObjectMapper();
                try{
                    List<String> list = objectMapper.readValue(userContactCategory.getGroupCategory(), new TypeReference<List<String>>() {});
                    //跟userIds合并
                    list.addAll(userIds);
                    //转化为字符串
                    String str = objectMapper.writeValueAsString(list);
                    userContactCategory.setGroupCategory(str);
                }catch (Exception e){
                    log.error("添加分组失败", e);
                    userContactCategory.setGroupCategory(userIds.toString());
                }
            }
            userContactCategory.setGroupCategory(userIds.toString());
        }
        userContactCategory.setUpdateTime(new Date());
        int update = userContactCategoryMapper.updateById(userContactCategory);
        if(update == 0){
            throw new BusinessException(ExceptionBizCodeEnum.UPDATE_FAILED);
        }
    }

    public record ContactCategoryParam(String categoryName, String userId, String categoryIntroduce, List<String> contactIds, Integer contactType){}
    @Override
    public R addGroupCategory(ContactCategoryParam contactCategoryParam) throws BusinessException {

        //查询分组名称是否重复
        List<UserContactCategory> categoryList = userContactCategoryMapper.selectList(new LambdaQueryWrapper<UserContactCategory>()
                .eq(UserContactCategory::getUserId, contactCategoryParam.userId())
                .eq(UserContactCategory::getType, contactCategoryParam.contactType())
                .orderByDesc(UserContactCategory::getSort));
        for (UserContactCategory category : categoryList) {
            if(Objects.equals(category.getCategoryName(), contactCategoryParam.categoryName())){
                return R.error("分组名称重复");
            }
        }
        //添加分组
        ObjectMapper objectMapper = new ObjectMapper();
        String json = null;
        try {
            json = objectMapper.writeValueAsString(contactCategoryParam.contactIds());
        } catch (JsonProcessingException e) {
            throw new BusinessException(ExceptionBizCodeEnum.JSON_SERIALIZE_EXCEPTION);
        }
        UserContactCategory userContactCategory = new UserContactCategory();
        userContactCategory.setCategoryName(contactCategoryParam.categoryName());
        userContactCategory.setDesc(contactCategoryParam.categoryIntroduce());
        userContactCategory.setType(contactCategoryParam.contactType());
        userContactCategory.setSort(categoryList.size() != 0?categoryList.get(0).getSort() + 1: 1);
        if(Objects.equals(contactCategoryParam.contactType, UserContactTypeEnum.GROUP.getType())){
            userContactCategory.setGroupCategory(json);
        }
        if(Objects.equals(contactCategoryParam.contactType, UserContactTypeEnum.USER.getType())){
            userContactCategory.setUserCategory(json);
        }
        this.createGroup(contactCategoryParam.userId, userContactCategory);
        return R.ok();
    }

    @Override
    public R updateCategory(UserContactCategoryController.ContactCategoryParam contactCategoryParam) throws BusinessException {
        UserContactCategory userContactCategory = new UserContactCategory();
        userContactCategory.setCategoryId(contactCategoryParam.categoryId());
        userContactCategory.setDesc(contactCategoryParam.desc());
        userContactCategory.setType(contactCategoryParam.type());
        userContactCategory.setCategoryName(contactCategoryParam.categoryName());
        userContactCategory.setUpdateTime(new Date());
        try{
            //添加分组
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(contactCategoryParam.groupOrUserIds());
            if(Objects.equals(contactCategoryParam.type(), UserContactTypeEnum.GROUP.getType())) userContactCategory.setGroupCategory(json);
            if(Objects.equals(contactCategoryParam.type(), UserContactTypeEnum.USER.getType())) userContactCategory.setUserCategory(json);
        }catch (Exception e){
            throw new BusinessException(ExceptionBizCodeEnum.JSON_SERIALIZE_EXCEPTION);
        }
        this.baseMapper.updateById(userContactCategory);
        return R.ok();
    }
}
